package com.fangcun.service.admin.Impl;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fangcun.bean.admin.agent.response.AgentShareBenefitsRuleDetail;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.exception.ProAffairException;
import com.fangcun.common.exception.ProRunTimeException;
import com.fangcun.entity.Agent;
import com.fangcun.entity.AgentShareBenefitsRule;
import com.fangcun.mapper.AgentMapper;
import com.fangcun.mapper.AgentShareBenefitsRuleMapper;
import com.fangcun.service.admin.AgentShareBenefitsRuleService;

/**
 * @作者： 陳曉鬆 @时间： 2020年8月18日 - 上午10:16:23 @description：->
 */
@Service("agentShareBenefitsRuleService")
public class AgentShareBenefitsRuleServiceImpl implements AgentShareBenefitsRuleService {

	@Autowired
	private AgentShareBenefitsRuleMapper agentShareBenefitsRuleMapper;
	@Autowired
	private AgentMapper agentMapper;

	@Override
	@Transactional
	public AgentShareBenefitsRuleDetail detail(Long agentId) throws ProAffairException {
		AgentShareBenefitsRuleDetail detail = agentShareBenefitsRuleMapper.selectByAgentId(agentId);
		if (detail == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return detail;
	}

	@Override
	@Transactional
	public void settingShareBenefits(AgentShareBenefitsRule request) throws ProAffairException {
		AgentShareBenefitsRuleDetail detail = agentShareBenefitsRuleMapper.selectByAgentId(request.getAgentId());
		Agent agent = agentMapper.selectByPrimaryKey(request.getAgentId());
		if (agent == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (agent.getParentId() != null && agent.getParentId().longValue() != 0) {
			request.setParentAgentId(agent.getParentId());
		}
		if (request.getShareType() == 1) {
			if (request.getNumericalValue().doubleValue() > 1) {
				throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
			}
		}
		if (detail == null) {
			if (agentShareBenefitsRuleMapper.insertSelective(request) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "设置分利失败");
			}
		} else {
			request.setId(detail.getId());
			if (agentShareBenefitsRuleMapper.updateByPrimaryKeySelective(request) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "设置分利失败");
			}
		}
	}

}
